Power Automate workflow from SPFx NOT as Anyone

In many scenarios, Power Automate flows are triggered automatically, such as when a list item is created or updated, when a file is uploaded, or when a scheduled event occurs. However, there are times when we want to trigger a flow programmatically from within our SPFx web part.

In this article, we’ll explore how to trigger a Power Automate directly from an SPFx web part using an authenticated HTTP request, without exposing the flow as an anonymous endpoint.

This approach protects your tenant, ensures secure execution, and gives you full control over who is allowed to trigger the workflow.

In this article, we’ll explore how to trigger a Power Automate workflow directly from an SPFx web part using an authenticated HTTP request, without exposing the flow as an anonymous endpoint.

This approach protects your tenant, ensures secure execution, and gives you full control over who is allowed to trigger the workflow.

Solution: Use “Any user in my tenant” or “Specific users in my tenant”.


Prerequisites

Build the Power Automate Flow

Power Automate flow design

First, we’ll create a simple flow that accepts two strings and echoes them back in the response.

Request Body JSON Schema


{
  "type": "object",
  "properties": {
    "stringone": {
      "type": "string"
    },
    "stringtwo": {
      "type": "string"
    }
  }
}
      

This allows your SPFx web part to send a JSON payload containing stringone and stringtwo.

Add a Response action:

Copy the HTTP URL from the trigger — this will be used in SPFx.

Now that Power Automate is fully configured, let’s take a look at our SPFx solution in action

SPFx Power Automate integration in action

Core Component Analysis

The solution is composed of three core parts:

  1. PowerAutomateSpfxWebPart.ts – The main web part class handling initialization and authentication
  2. PowerAutomateSpfx.tsx – The React component providing the user interface
  3. package-solution.json – Configuration file defining required API permissions

Component Structure

The PowerAutomateSpfx component is a class-based React component that provides an intuitive interface for triggering Power Automate flows from SharePoint:


interface IPowerAutomateSpfxState {
  responseMessage: string;
  isLoading: boolean;
}

export default class PowerAutomateSpfx extends React.Component<IPowerAutomateSpfxProps, IPowerAutomateSpfxState>
      

1. State Management

The component manages two crucial state properties:

2. Flow Trigger Handler

The heart of the integration lies in the handleTriggerFlow method:


private handleTriggerFlow = async (): Promise<void> => {
  this.setState({ isLoading: true, responseMessage: 'Triggering flow...' });
  
  const requestBody = {
    Title: 'Test from SPFx',
    UserEmail: this.props.userEmail
  };
  
  try {
    const response = await this.props.triggerFlow(requestBody, this.props.url);
    this.setState({ 
      isLoading: false, 
      responseMessage: `Success: ${JSON.stringify(response, null, 2)}` 
    });
  } catch (error: any) {
    this.setState({ 
      isLoading: false, 
      responseMessage: `Error: ${error.message || 'Unknown error occurred'}` 
    });
  }
}
      

This method:

3. User Interface Design

The render method creates a responsive interface that:


<button
  type="button"
  onClick={() => this.handleTriggerFlow()}
  disabled={this.state.isLoading}
  style={{
    padding: '10px 20px',
    backgroundColor: this.state.isLoading ? '#ccc' : '#0078d4',
    color: 'white',
    border: 'none',
    borderRadius: '3px',
    cursor: this.state.isLoading ? 'not-allowed' : 'pointer'
  }}
>
  {this.state.isLoading ? 'Processing...' : 'Trigger Power Automate Flow'}
</button>
      

Props Interface Design

The component's props interface demonstrates thoughtful design for SPFx integration:


export interface IPowerAutomateSpfxProps {
  url: string;
  isDarkTheme: boolean;
  environmentMessage: string;
  hasTeamsContext: boolean;
  userDisplayName: string;
  userEmail: string;
  triggerFlow: (body: any, flowUrl: string) => Promise<any>;
}
      

Authentication and API Integration

Web Part Implementation

The PowerAutomateSpfxWebPart.ts file handles the complex authentication logic:


private triggerFlow = async (body: any, flowUrl: string): Promise<any> => {
  try {
    const client = await this.context.aadHttpClientFactory
      .getClient('https://service.flow.microsoft.com/');
    
    const response = await client.post(flowUrl, AadHttpClient.configurations.v1, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(body)
    });

    if (response.ok) {
      const responseData = await response.json();
      console.log('Flow triggered successfully', responseData);
      return responseData;
    } else {
      const errorText = await response.text();
      console.error('Flow trigger failed', response.status, response.statusText, errorText);
      throw new Error(`HTTP ${response.status}: ${response.statusText}${errorText ? ' - ' + errorText : ''}`);
    }
  } catch (error) {
    console.error('Error calling flow', error);
    throw error;
  }
}
      

This implementation:

API Permissions Setup

The package-solution.json file contains a crucial configuration for Power Automate integration:


{
  "solution": {
    "name": "power-automate-spfx-client-side-solution",
    "id": "808c9e90-6714-4ae5-8b5c-c96b1410220b",
    "version": "1.0.0.0",
    "includeClientSideAssets": true,
    "skipFeatureDeployment": true,
    "isDomainIsolated": false,
    "developer": {
      "webApiPermissionRequests": [
        {
          "resource": "Microsoft Flow Service",
          "scope": "User"
        }
      ]     
    }
  }
}
      

Packaging and Deployment

Run the production build:


gulp bundle --ship
gulp package-solution --ship
      

Upload .sppkg to the App Catalog, grant permissions, configure the property pane with your flow URL, and test.


Conclusion

This solution is an excellent starting point for securely bridging SPFx and Power Automate. It demonstrates best practices and provides a solid foundation for more advanced integration scenarios.

View the sample resources on GitHub: Execute Power Automate workflow from SPFx – GitHub Resources

Clavin Fernandes
Clavin Fernandes
Microsoft Business Applications MVP | Power Platform | AI & Low-code